/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.servlets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.ActionOnElement;
import model.DHTMLConstants;
import model.Vocabulary;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.jtb.quickr.PhotoResponse;
import org.jtb.quickr.PhotosResponse;
import org.jtb.quickr.PhotosSearchCriteria;
import org.jtb.quickr.PhotosService;
import org.jtb.quickr.QuickrException;
import org.myontology.controller.AttributeHolder;
import org.myontology.controller.WebAttributeHolder;
import org.myontology.controller.impl.CloudAction;
import org.myontology.db.HibernateSessionProvider;
import org.myontology.db.SessionWrapper;
import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;

import view.HTMLUIcomponents.AbstractComponent;
import controller.HelperFunctions;
import controller.WikipediaParser;
import controller.elementMapper.ClassMapper;
import controller.elementMapper.Mapper;
import controller.elementMapper.OntologyModuleMapper;
import controller.elementMapper.PropertyMapper;
import controller.sesameDataConnector.AbstractDataConnector;


/**
 * Servlet implementation class for Servlet: AjaxXmlGeneratorhttp://myontology.deri.at/prototype_itday/
 *
 */
 public class AjaxXmlGenerator extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */

	private static final long serialVersionUID = 1; // do not know why...
	 	
	public static Logger logger = Logger.getLogger(AjaxXmlGenerator.class);
	
	
	
	
	public AjaxXmlGenerator() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		

		
//		if ( !UserBean.is_loged_on( request.getSession().getId() ) ) {			
//			response.sendRedirect( request.getContextPath() + "/login");
//			return;
//		}
		
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		
		String ret = "";
		int actionCode = Integer.parseInt( request.getParameter("actionCode") );
		
		if( actionCode <= 0 ) {
			return;
		}
		
		else if ( actionCode == DHTMLConstants.GETMOREINFO ) {

			ret += "<more><![CDATA[";
			try {
				String id = request.getParameter( "id" );
				URI uri =AbstractDataConnector.getURI( id );
					
				String comment = Mapper.selectComment( uri, Vocabulary.ENGLISH );
				comment = HelperFunctions.getShortHTMLComment(comment);
				comment = comment.replace("\n", "<br />");
				
				ret += StringEscapeUtils.escapeJavaScript( comment ); 
			}
			catch( Exception e ) {
				
			}
			ret += "]]></more>";
		}
	
		else if ( actionCode == DHTMLConstants.CHECKIFURLISREACHABLE) {
			// test, if given uri is reachable

			ret += "<seeAlsoReachability>";
			
		  	String url = request.getParameter( "uri" );
			if (url != null) {
				if (!AbstractDataConnector.isURLreachable(new URIImpl(url))) {

					
					ret += "<elementid><![CDATA["+request.getParameter( "elementid" )+"]]></elementid>";
					ret += "<uri><![CDATA["+request.getParameter( "uri" )+"]]></uri>";
					//System.out.println("sent for " + url);
					
				}
				// else is not needed; if reachable nothing has to be changed
			}	
			ret += "</seeAlsoReachability>";		
		}
		else if ( actionCode == DHTMLConstants.SEARCHYOUTUBEBYID) {
			// Searches in Quickr API for Flickr photos with Tags as specified in "input"-parameter
			ret += "<youtubesearchid>";

			try {
				// need to know: thumbnail and URI.
				
				String id = request.getParameter( "input" );
				
				org.w3c.dom.Document document = HelperFunctions.ParseYouTubeRESTget_details(id);

				String thumbnail_url = "";

				org.w3c.dom.NodeList list = document.getFirstChild().getFirstChild().getChildNodes();
				Boolean found = false;
				int j = 0;
				while( found==false && j < list.getLength() ) {
					if( list.item( j ).getNodeName().equals("thumbnail_url")) {
						logger.debug( "thumbnail_url found");
						thumbnail_url = list.item(j).getTextContent();
						found = true;
					}					
					j++;
				}
				
				if( found == true ){

					ret += "<id><![CDATA[" + id + "]]></id>";
					ret += "<thumbnail_url><![CDATA[" + thumbnail_url + "]]></thumbnail_url>";
				}
				//System.out.println( ret );
					
			} catch (Exception qe) {
				logger.error(qe);
			}		
			
			ret += "</youtubesearchid>";
		}
		else if ( actionCode == DHTMLConstants.SEARCHYOUTUBEBYTAGS) {
			// Searches in Quickr API for Flickr photos with Tags as specified in "input"-parameter
			ret += "<youtubesearchtags>";

			try {

				String per_page = request.getParameter( "per_page" );
				String page = request.getParameter( "page" );
				String input = request.getParameter( "input" );
				int total = 0;
				
				String tmp ="http://www.youtube.com/api2_rest?method=youtube.videos.list_by_tag&dev_id=jpZw5IQr-HI&tag=";				
				tmp += java.net.URLEncoder.encode( input,"UTF-8");				
				tmp += "&page=" + page + "&per_page=" + per_page; 
				
				java.net.URL url = new java.net.URL( tmp );
				
				BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
				Boolean hasNext = br.ready();

				if( hasNext ) {
					br.readLine(); // leave first line (is <?xml version="1.0" encoding="utf-8"?>)
					while(hasNext) {
						String line = br.readLine();
						if( line==null ){
							hasNext = false;
						}
						else {
							ret += line;
							if( line.contains("<video>"))
								total++;
						}					
					}
				}
				

				ret += "<metadata>";
				ret += "<page>" +page + "</page>";
				ret += "<per_page>" + per_page + "</per_page>";
				ret += "<actioncode>" + actionCode + "</actioncode>";
				ret += "<input>" + input + "</input>";
				ret += "</metadata>";
				
				
				
				//System.out.println( ret );
					
			} catch (Exception qe) {
				logger.error(qe);
			}		
			
			ret += "</youtubesearchtags>";
		}
		else if ( actionCode == DHTMLConstants.SEARCHFLICKRIMAGESBYID) {
			// Searches in Quickr API for Flickr photos with Tags as specified in "input"-parameter
			ret += "<flickrsearchid>";
			
			try {
				
				PhotosService ps = new PhotosService();
				
				PhotoResponse photo = ps.getInfo(java.net.URLEncoder.encode(request.getParameter( "input" ),"UTF-8"));
				
				if( photo != null ){
					// on client side the ID and the URI is needed.
					ret += "<id>" + photo.getPhotoId() + "</id>";
					ret += "<thumb>" + photo.getThumbnailUrl() + "</thumb>";
					ret += "<small>" + photo.getSmallUrl() + "</small>";
				}			
				//System.out.println( ret );
					
			} catch (QuickrException qe) {
				logger.error(qe);
			}		
			
			ret += "</flickrsearchid>";
		}
		
		else if ( actionCode == DHTMLConstants.SEARCHFLICKRIMAGESBYTAGS) {
			// Searches in Quickr API for Flickr photos with Tags as specified in "input"-parameter
			ret += "<flickrsearch>";

			PhotosSearchCriteria c = new PhotosSearchCriteria();				
			
			String[] strarray = request.getParameter( "input" ).split(" ");
			java.util.TreeSet<String> list = new TreeSet<String>();			
			for( int i=0; i<strarray.length; i++) {
				list.add(java.net.URLEncoder.encode(strarray[i],"UTF-8"));
			}			
			c.setTags( list );
			c.setPage( Integer.parseInt( request.getParameter( "page" ) ) ); // the start of the page
			c.setPerPage( Integer.parseInt( request.getParameter( "perpage" ) ) ); // how many items are returned

			ret += this.SearchFlickrAndGetXML(c, actionCode, request.getParameter( "input" ));
							
			ret += "</flickrsearch>";
		}
		
		else if ( actionCode == DHTMLConstants.SEARCHFLICKRIMAGESBYTEXT) {
			// Searches in Quickr API for Flickr photos with Tags as specified in "input"-parameter
			ret += "<flickrsearch>";

			PhotosSearchCriteria c = new PhotosSearchCriteria();
			String s = request.getParameter( "input" );
			s = java.net.URLEncoder.encode(s,"UTF-8");
			
			c.setText( s );
			c.setPage( Integer.parseInt( request.getParameter( "page" ) ) ); // the start of the page
			c.setPerPage( Integer.parseInt( request.getParameter( "perpage" ) ) ); // how many items are returned
			
			ret += this.SearchFlickrAndGetXML(c, actionCode, request.getParameter( "input" ));
			
			ret += "</flickrsearch>";
		}
		
		else if( actionCode == DHTMLConstants.TITLEEXISTS ) {
			ret += "<giveSimilarMatches>";

			String[] viewtypes = request.getParameterValues( "viewtype" );
			String input = request.getParameter( "input" );
			
			final int COUNT = 8; // How many elements will be returned in maximum.
			
			ArrayList<ArrayList<URI>> typeListAll = new ArrayList<ArrayList<URI>>();
							
			for( int i = 0; viewtypes!=null && i<viewtypes.length; i++ ) {

				// types[ i ] = types[ i ].replace("%23", "#" ); // for parameters containing "#"
				String viewtype = viewtypes[ i ];
				ArrayList<URI> tmp = new ArrayList<URI>();

				// select ones which contain the word:
				if( viewtype.equals( DHTMLConstants.CLASS_VIEWTYPE ))
					tmp = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.CLASS, input, COUNT);
				else if( viewtype.equals( DHTMLConstants.PROPERTY_VIEWTYPE )) {
					ArrayList<URI> tmpDP = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.DATATYPEPROPERTY, input, COUNT);

					ArrayList<URI> tmpOP = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.OBJECTPROPERTY, input, COUNT);
					
					if( tmpDP!=null ) {
						// mix the elements
						int j = 0;
						while( tmp.size()<=COUNT && j<=COUNT) {
							
							if( tmpDP!=null && tmpDP.size()>j ) {
								tmp.add( tmpDP.get(j));
							}
							if( tmpOP!=null && tmpOP.size()>j ) {
								tmp.add( tmpOP.get(j));
							}
							
							j++;
						}
					}
					else
						tmp = tmpOP;
					
				}
				else if( viewtype.equals( DHTMLConstants.ONTOLOGY_VIEWTYPE ))
					tmp = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.ONTOLOGYMODULE, input, COUNT);

				if( tmp!=null && tmp.size()>0 ) {
					typeListAll.add( tmp );
				}
			}
			
			if( typeListAll.size()>0 ) {
				
				int countFound = 0;
				Iterator<ArrayList<URI>> i0 = typeListAll.iterator();
				while( i0.hasNext() ) {
	
					ArrayList<URI> tmp = i0.next();
					countFound += tmp.size();
				}

				Iterator<ArrayList<URI>> i1 = typeListAll.iterator();
				while( i1.hasNext() ) {
					ArrayList<URI> tmp = i1.next();

					double countTmp = tmp.size();
					double max = (countTmp * COUNT / countFound); // 0.3 to round down
					
					double maxOfThisList = countTmp<max ? countTmp : max;
					
					Iterator<URI> iter = tmp.iterator();					
					// put this items into the XML-document:
					int i = 0;
					while( i<maxOfThisList && iter.hasNext() ) {
						i++;
										
						URI id = iter.next();
		
						
						try {
							String label = ClassMapper.selectLabel( id, Vocabulary.ENGLISH );
							String comment = ClassMapper.selectComment( id, Vocabulary.ENGLISH );
							
							if( comment==null )
								comment = AbstractComponent.NOTHINGSELECTED;
							
							ret +=
								"<item>" +
								"<uri><![CDATA[" + response.encodeURL(id.stringValue()) + "]]></uri>" +
								"<label><![CDATA[" + StringEscapeUtils.escapeHtml( label ) + "]]></label>" +
								"<comment><![CDATA[" + StringEscapeUtils.escapeHtml( comment ) + "]]></comment>" +
								"</item>";
						} catch( Exception e ) {
							logger.error(e);
						}
					}
				}
			}			

			ret += "</giveSimilarMatches>";			
		}
		
		else if( actionCode == DHTMLConstants.SUGGEST ) {
			ret += "<giveSimilarMatches>";
			
			String[] viewtypes = request.getParameterValues( "viewtype" );
			String input = request.getParameter( "input" );
			
			final int COUNT = 8; // How many elements will be returned in maximum.
			
			ArrayList<ArrayList<URI>> typeListAll = new ArrayList<ArrayList<URI>>();
							
			for( int i = 0; viewtypes!=null && i<viewtypes.length; i++ ) {

				// types[ i ] = types[ i ].replace("%23", "#" ); // for parameters containing "#"
				String viewtype = viewtypes[ i ];
				// URI type = new URIImpl( types[ i ] );
				
				// request an array with the matching items:
				ArrayList<URI> tmp = new ArrayList<URI>();
				

				if( input==null || input.equals("") ) {

					// fill from recently viewed items:
					HttpSession session = request.getSession();
					int count = 0;
					
					ActionOnElement val = (ActionOnElement)session.getAttribute( "clickhistory[" + (count++) + "]" );

					while( val!=null && tmp.size()<COUNT ) {
				
						if( viewtype.equals( val.getViewtype() ) ) {

							if( !tmp.contains( val.getUri() ) )
								tmp.add( val.getUri() );
						}

						val = (ActionOnElement)session.getAttribute( "clickhistory[" + (count++) + "]" );
					}

					
					// fill the rest with the rankedElements of given type:				
					if( tmp == null || tmp.size()<COUNT ) {
						
						if( tmp==null )
							tmp = new ArrayList<URI>();
					
						AttributeHolder attributes = new WebAttributeHolder(request);
						SessionWrapper s = (SessionWrapper)new HibernateSessionProvider().create(attributes);
						s.init();
						String typ="";
						if (viewtype.equals("ct"))
							typ="Class";
						else if (viewtype.equals("ot"))
							typ = "OntologyModule";
						else if (viewtype.equals("pt"))
							typ = "Property";
						
//						ArrayList<URI> rankedUris = ElementRanker.getSubList( viewtype, COUNT );
						List<URI> rankedUris = new ArrayList<URI>();
						try {
							rankedUris = CloudAction.loadRankedURIs(typ, s.connection().createStatement());
						} catch (Exception e) {
							logger.error("error loading rankedUris",e);
						} 
						s.finish();
						if( rankedUris!=null ) {
							
							Iterator<URI> iter = rankedUris.iterator();						
							while( iter.hasNext() && tmp.size()<COUNT ) {
								
								URI next = iter.next();
								if( !tmp.contains( next ) )
									tmp.add( next );
							}
						}
					}
				}
				else {
					
					// select ones which contain the word:
					if( viewtype.equals( DHTMLConstants.CLASS_VIEWTYPE ))
						tmp = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.CLASS, input, COUNT);
					else if( viewtype.equals( DHTMLConstants.PROPERTY_VIEWTYPE )) {
						ArrayList<URI> tmpDP = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.DATATYPEPROPERTY, input, COUNT);

						ArrayList<URI> tmpOP = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.OBJECTPROPERTY, input, COUNT);
						
						if( tmpDP!=null ) {
							// mix the elements
							int j = 0;
							while( tmp.size()<=COUNT && j<=COUNT) {
								
								if( tmpDP!=null && tmpDP.size()>j ) {
									tmp.add( tmpDP.get(j));
								}
								if( tmpOP!=null && tmpOP.size()>j ) {
									tmp.add( tmpOP.get(j));
								}
								
								j++;
							}
						}
						else
							tmp = tmpOP;
						
					}
					else if( viewtype.equals( DHTMLConstants.ONTOLOGY_VIEWTYPE ))
						tmp = controller.sesameDataConnector.AbstractDataConnector.getMatchingElements( Vocabulary.ONTOLOGYMODULE, input, COUNT);
				}
				
				
				
				
				
				if( tmp!=null && tmp.size()>0 ) {
					typeListAll.add( tmp );
				}
			}
			
			
			if( typeListAll.size()>0 ) {
				
				int countFound = 0;
				Iterator<ArrayList<URI>> i0 = typeListAll.iterator();
				while( i0.hasNext() ) {
	
					ArrayList<URI> tmp = i0.next();
					countFound += tmp.size();
				}

				Iterator<ArrayList<URI>> i1 = typeListAll.iterator();
				while( i1.hasNext() ) {
					ArrayList<URI> tmp = i1.next();

					double countTmp = tmp.size();
					double max = (countTmp * COUNT / countFound); // 0.3 to round down
					
					double maxOfThisList = countTmp<max ? countTmp : max;
					
					Iterator<URI> iter = tmp.iterator();					
					// put this items into the XML-document:
					int i = 0;
					while( i<maxOfThisList && iter.hasNext() ) {
						i++;
										
						URI id = iter.next();
						
						try {
							String label = ClassMapper.selectLabel( id, Vocabulary.ENGLISH );
							String comment = ClassMapper.selectComment( id, Vocabulary.ENGLISH );
							
							if( comment==null )
								comment = AbstractComponent.NOTHINGSELECTED;
							
							ret +=
								"<item>" +
								"<id><![CDATA[" + response.encodeURL(id.stringValue()) + "]]></id>" +
								"<name><![CDATA[" + /*StringEscapeUtils.escapeHtml( label )*/ label + "]]></name>" +
								"<csstype><![CDATA[" + HelperFunctions.getCSSTypeByUri( id ) + "]]></csstype>" +
								// "<comment>" + StringEscapeUtils.escapeHtml( comment ) + "</comment>" +
								"</item>";
						} catch( Exception e ) {
							logger.error(e);
						}
					}
				}
			}

			
			ret += "</giveSimilarMatches>";		
		}
		
		else if(  actionCode == DHTMLConstants.CLASSESBELONGINGTOOM ) {
			// return XML-file containing classes, which belong to given OntologyModule
			
			try {
				
				ArrayList<URI> array1 = new ArrayList<URI>();
				
				String url = request.getParameter( "id" );
				if (url.compareTo( DHTMLConstants.ALLONTOLOGYMODULES ) == 0) {

					ArrayList<URI> tmp = ClassMapper.selectAll();
					if( tmp!=null ) 
						array1.addAll( tmp );
				}
				else if (url.compareTo( DHTMLConstants.NOONTOLOGYMODULE ) == 0) {
					ArrayList<URI> array2 = ClassMapper.selectAll();
					if( array2!=null) {
						for (int i = 0; i < array2.size(); i ++) {
							
							ArrayList<URI> tmp = ClassMapper.selectBelongsToOM(array2.get(i));
							
							if( tmp==null || tmp.size()==0 ) 
								array1.add( array2.get(i) );	
						}
					}
				}
				else if (url.compareTo( DHTMLConstants.PREDEFINEDDATATYPE) == 0) {

					array1.add( Vocabulary.XMLSBOOLEAN );
					array1.add( Vocabulary.XMLSDATETIME );
					array1.add( Vocabulary.XMLSDOUBLE );
					array1.add( Vocabulary.XMLSINTEGER );
					array1.add( Vocabulary.XMLSSTRING );
				}
				else {
					array1 = OntologyModuleMapper.selectClassesBelongingToOM( new URIImpl( url ) );
				}
				
				
				ret += "<classesbtom>\n";
				
				for (int i = 0; i < array1.size(); i++) {
					ret += "<id><![CDATA[" + array1.get(i) + "]]></id>\n";
					ret += "<label><![CDATA[" + Mapper.selectLabel( array1.get(i), Vocabulary.ENGLISH ) + "]]></label>\n";
				}
				
				ret += "<formname>" + request.getParameter( "formname" ) + "</formname>\n";
				
				ret += "</classesbtom>";

			} catch( Exception e ) {
				logger.error( e.getMessage() + "id: " + request.getParameter( "id" ) );
			}		
		}		

		else if(  actionCode == DHTMLConstants.SYNONYMCHECK ) {
			
			ret += "<wordnet>";
			String input = request.getParameter( "input" );
			String wordnetText = HelperFunctions.getWordNetText(input);
			
			if (wordnetText != "") {
				ret += "<syns>" + wordnetText + "</syns>";
				// ret += "<syns><![CDATA[" + wordnetText + "]]></syns>";
			}
			

			
			ret += "</wordnet>";	
			
		}
		
		else if (actionCode == DHTMLConstants.WORDNETENTRY) {
			
			ret += "<wordnet2>";
			String input = request.getParameter("input");
			String wordnetText = HelperFunctions.getWordNetText(input);
			
			if (wordnetText != "") {
				ret += "<syns>" + wordnetText + "</syns>";
				// ret += "<syns><![CDATA[" + wordnetText + "]]></syns>";
			}
			
			ret += "</wordnet2>";
		}
		
		else if(  actionCode == DHTMLConstants.PROPERTIESBELONGINGTOOM ) {
			// return XML-file containing objectproperties, which belong to given OntologyModule

			try {
				
				ArrayList<URI> array1 = new ArrayList<URI>();
				
				String url = request.getParameter( "id" );

				if (url.compareTo( DHTMLConstants.ALLONTOLOGYMODULES ) == 0) {
					
					array1 = PropertyMapper.selectAll();					
				}
				else if (url.compareTo( DHTMLConstants.NOONTOLOGYMODULE ) == 0) {

					ArrayList<URI> array2 = PropertyMapper.selectAll();

					if( array2!=null ) {
						for (int i = 0; i < array2.size(); i ++) {
	
							ArrayList<URI> tmp = PropertyMapper.selectBelongsToOM(array2.get(i));
							
							if( tmp==null || tmp.size()==0 ) 
								array1.add( array2.get(i) );
							
						}
					}
				}
				else {
					
					array1 = OntologyModuleMapper.selectPropertiesOfOM( new URIImpl( url ) );
				}
				
				ret += "<propertiesbtom>\n";
				
				for (int i = 0; i < array1.size(); i++) {
					ret += "<id><![CDATA[" + array1.get(i) + "]]></id>\n";
					ret += "<label><![CDATA[" + Mapper.selectLabel( array1.get(i), Vocabulary.ENGLISH ) + "]]></label>\n";
				}
				
				ret += "<formname>" + request.getParameter( "formname" ) + "</formname>\n";
				
				ret += "</propertiesbtom>";

			} catch( Exception e ) {
				logger.error( e.getMessage() + "id: " + request.getParameter( "id" ) );
			}
		}

		else if(  actionCode == DHTMLConstants.WIKIPEDIAENTRY ) {
			
			ret += "<wikipediaResult>";
			String input = request.getParameter( "input" );
			
			String wikiText = ""; 
			controller.WikipediaParser p = new WikipediaParser();
			String url = "http://en.wikipedia.org/wiki/" + input;
			p.parseURL( url, 1 );
			
			wikiText = p.text;
			
			ret += "<![CDATA[";				
			if (wikiText!="") {
				ret += "<p>The first paragraph of <a href=\"" + url + "\" target=\"_blank\" >" + url + "</a> is: </p>";
				ret += "<p>" + wikiText + "</p>";
			}
			else {
				ret += "<p>Nothing found on <a href=\"http://en.wikipedia.org\" target=\"_blank\" >http://en.wikipedia.org</a> for the given value.</p>";
			}

			ret += "]]>";
			
			ret += "</wikipediaResult>";	
			
		}

		else if( actionCode == DHTMLConstants.MARKASDEPRICATED ) {
			
			String id = request.getParameter( "id" );
			URI uri =AbstractDataConnector.getURI( id );
			if( uri!=null ) {
				
				try { 
					Mapper.markAsDeprecated( uri );
				}
				catch( Exception e ) {
					
				}
			}

            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/GetFormInViewMode?id=" + request.getParameter( "id" ) + "&cssidcontent=" + view.HTMLUIcomponents.Label.CSSIDCONTENT_TITLE); 
            dispatcher.forward(request,response);
			
		}

		else if( actionCode == DHTMLConstants.MARKASNONDEPRICATED ) {
			
			String id = request.getParameter( "id" );
			URI uri =AbstractDataConnector.getURI( id );
			if( uri!=null ) {
				
				try { 
					Mapper.markAsNonDeprecated( uri );
				}
				catch( Exception e ) {
					
				}
			}

            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/GetFormInViewMode?id=" + request.getParameter( "id" ) + "&cssidcontent=" + view.HTMLUIcomponents.Label.CSSIDCONTENT_TITLE); 
            dispatcher.forward(request,response);
			
		}
		
		

		
		
	    PrintWriter out = response.getWriter();
		
	    out.println("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
	    
	    out.println( ret );
	}
		
	
	/**
	 * 
	 * @param c
	 * @param actioncode
	 * @param input	The String which was given by the user to query 
	 * @return
	 */
	private String SearchFlickrAndGetXML( PhotosSearchCriteria c, int actioncode, String input ) {
		String ret = "";

		try {				
			PhotosService ps = new PhotosService();
						
			PhotosResponse photos = ps.search( c );
			
			
			for( int i=0; i<photos.getPhotos().size(); i++ ){
				// on client side the ID and the URI is needed.
				ret += "<photo>";
				ret += "<id>";
				ret += photos.getPhotos().get(i).getPhotoId();
				ret += "</id>";
				ret += "<thumb>";
				ret += photos.getPhotos().get(i).getThumbnailUrl();
				ret += "</thumb>";
				ret += "<small>";
				ret += photos.getPhotos().get(i).getSmallUrl();
				ret += "</small>";					
				ret += "</photo>";
			}

			
			ret += "<total>" + photos.getTotal() + "</total>";
			ret += "<page>" + photos.getPage() + "</page>";
			ret += "<pages>" + photos.getPages() + "</pages>";
			ret += "<perpage>" + photos.getPerPage() + "</perpage>";
			ret += "<actioncode>" + actioncode + "</actioncode>";
			ret += "<input>" + input + "</input>";
			
			
			//System.out.println( ret );
				
		} catch (QuickrException qe) {
			logger.error(qe);
		}
		
		
		return ret;
	}
}
